package com.bawei.module_live.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_live.databinding.ItemMoreLiveBinding
import com.bawei.module_live.data.LiveData
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import android.widget.ImageView

class MoreLiveAdapter(
    private val context: Context
) : RecyclerView.Adapter<MoreLiveAdapter.MoreLiveViewHolder>() {

    private val liveDataList = mutableListOf<LiveData>()

    // 点击进入直播间监听器
    private var onEnterLiveRoomListener: ((liveData: LiveData, position: Int) -> Unit)? = null

    // ViewHolder
    inner class MoreLiveViewHolder(private val binding: ItemMoreLiveBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(liveData: LiveData, position: Int) {
            // 标签
            binding.tvTag.text = "红包" // 或根据liveData动态设置

            //主播头像
            Glide.with(context)
                .load(liveData.videomainimag)
                .centerCrop()
                .transform(CenterCrop())
                .into(binding.ivAuthor)

            // 主播名
            binding.tvAuthor.text = liveData.name

            // 标题/描述
            binding.tvTitle.text = "${liveData.name}正在直播"// 或 liveData.title

            // 观看数
            binding.tvViewers.text = "${liveData.commentnum}人观看"

            // 加载缩略图
            Glide.with(context)
                .load(liveData.videomainimag)
                .centerCrop()
                .transform(CenterCrop(), RoundedCorners(10))
                .into(binding.ivThumbnail)

            // 设置点击进入直播间监听
            itemView.setOnClickListener {
                onEnterLiveRoomListener?.invoke(liveData, position)
            }
        }
    }

    // Adapter 核心方法
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MoreLiveViewHolder {
        val binding = ItemMoreLiveBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return MoreLiveViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MoreLiveViewHolder, position: Int) {
        val liveData = liveDataList[position]
        holder.bind(liveData, position)
    }

    override fun getItemCount(): Int = liveDataList.size

    // 数据更新
    fun setData(data: List<LiveData>) {
        liveDataList.clear()
        liveDataList.addAll(data)
        notifyDataSetChanged()
    }

    fun addData(data: List<LiveData>) {
        val startPos = liveDataList.size
        liveDataList.addAll(data)
        notifyItemRangeInserted(startPos, data.size)
    }

    // 设置进入直播间监听器
    fun setOnEnterLiveRoomListener(listener: (liveData: LiveData, position: Int) -> Unit) {
        onEnterLiveRoomListener = listener
    }
}


